import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { checkTokenValidity } from '../utils/request'
import { ElMessage } from 'element-plus'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录 - 后台管理系统'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: {
      title: '注册 - 后台管理系统'
    }
  },

  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页 - 后台管理系统',
      requiresAuth: true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta: {
      title: '用户管理 - 后台管理系统',
      requiresAuth: true
    }
  },
  {
    path: '/role',
    name: 'Role',
    component: () => import('../views/Role.vue'),
    meta: {
      title: '邀请码 - 后台管理系统',
      requiresAuth: true
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/Settings.vue'),
    meta: {
      title: 'CormfUI日志管理 - 后台管理系统',
      requiresAuth: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: {
      title: '个人中心 - 后台管理系统',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局导航守卫，设置页面标题
router.beforeEach(async (to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
  if (to.meta.requiresAuth) {
    try {
      const isTokenValid = await checkTokenValidity()
      if (isTokenValid) {
        next()
      } else {
        localStorage.setItem('redirectAfterLogin', to.fullPath)
        ElMessage.warning('登录已过期，请重新登录')
        next('/login')
      }
    } catch (error) {
      localStorage.setItem('redirectAfterLogin', to.fullPath)
      next('/login')
    }
  } else {
    if ((to.path === '/login')) {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const isTokenValid = await checkTokenValidity()
          if (isTokenValid) {
            next('/dashboard')
            return
          }
        } catch (error) {}
      }
    }
    next()
  }
})

export default router 